<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/10/19
 * Time: 11:09
 */

namespace app\api\controller;

use pay\Paypal;
use pay\Upacp;
use pay\Wx;
use pay\Ali;
use think\Controller;
use think\Db;

class Timing extends Controller
{
    /**
     * 优惠券状态->下架
     * 我的优惠券状态->过期
     * 每分钟一次---已跑
     */
    public function couponStatus(){
        $date = date('Y-m-d');
        Db::table('up_my_coupon')->where('mc_status', 1)->where('mc_use_end_time', '<', $date)->setField('mc_status', 3);
        Db::table('up_coupon')->where('coupon_status', 1)->where('coupon_use_end_time', '<', $date)->setField('coupon_status', 2);
    }
    
    /**
     * 发送优惠券
     * 每分钟一次---已跑
     */
    public function sendCoupon(){
        $datetime = date('Y-m-d H:i:s');
        $coupon = Db::table('up_coupon')
            ->where('coupon_status', 1)
            ->where('coupon_is_send', 1)
            ->where('coupon_send_time', '<=', $datetime)
            ->field('coupon_id, coupon_range, coupon_user_ids')
            ->find();
        if($coupon){
            Db::startTrans();
            try{
                // 修改发送状态
                Db::table('up_coupon')->where('coupon_id', $coupon['coupon_id'])->setField('coupon_is_send', 2);
                // 插入消息表
                $notice = [
                    'notice_title' => '新优惠券',
                    'notice_content' => '新优惠券',
                    'notice_range' => $coupon['coupon_range'],
                    'notice_type' => 2,
                    'notice_coupon_id' => $coupon['coupon_id'],
                    'notice_read_user' => ',0,',
                    'notice_del_user' => ',0,',
                    'notice_time' => date('Y-m-d H:i:s')
                ];
                if($coupon['coupon_range'] == 1){
                    $notice['notice_user'] = ',' . $coupon['coupon_user_ids'] . ',';
                }else{
                    $notice['notice_user'] = -1;
                }
                Db::table('up_notice')->insert($notice);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    
    /**
     * 初始化今日浏览人数-->0
     * 每日00:00:00---已跑
     */
    public function initLookNum(){
        Db::table('up_goods')->where('goods_look_num', '>', 0)->setField('goods_look_num', 0);
    }
    
    /**
     * 更新抽奖状态
     * 每日00:00:00---已跑
     */
    public function drawStatus(){
        $date = date('Y-m-d');
        // 未开始->进行中
        Db::table('up_draw')
            ->where('draw_status', 1)
            ->where('draw_begin_date', '<', $date)
            ->setField('draw_status', 2);
        // 进行中->已结束
        Db::table('up_draw')
            ->where('draw_status', 2)
            ->where('draw_end_date', '<', $date)
            ->setField('draw_status', 3);
    }
    
    /**
     * 超过截止日期，没有画师应征或者没有选画师的约稿，自动设置为失效
     * 每日00:00:00---已跑
     */
    public function loseYue(){
        $date = date('Y-m-d');
        // 应征中->已失效
        Db::table('up_yue')
            ->where('yue_status', 1)
            ->where('yue_end_time', '<', $date)
            ->where('yue_is_call', 1)
            ->setField('yue_status', 6);
    }
    
    /**
     * 正常商品、秒杀商品半个小时未付款，取消订单，释放库存
     * 分钟执行一次--已跑
     */
    public function orderStatus(){
        $datetime = date('Y-m-d H:i:s', strtotime('-30 minute'));
        $order = Db::table('up_goods_order')
            ->where('order_type', 'IN', '1,3')
            ->where('order_status', 1)
            ->where('order_create_time', '<=', $datetime)
            ->field('order_num, order_goods_id, order_spec_id, order_id')
            ->select();
        if($order){
            Db::startTrans();
            try{
                foreach($order as $k => $v){
                    // 订单状态
                    Db::table('up_goods_order')
                        ->where('order_id', $v['order_id'])
                        ->update([
                            'order_canecl_time' => date('Y-m-d H:i:s'),
                            'order_status' => 8
                        ]);
                    // 释放库存
                    Db::table('up_goods_spec')->where('spec_id', $v['order_spec_id'])->setInc('spec_stock', $v['order_num']);
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    
    /**
     * 约稿商品半个小时未付款，取消订单，约稿状态改成失效
     * 每分钟--已跑
     */
    public function yueOrderStatus(){
        $datetime = date('Y-m-d H:i:s', strtotime('-30 minute'));
        $order = Db::table('up_goods_order')
            ->where('order_type', 4)
            ->where('order_status', 1)
            ->where('order_create_time', '<=', $datetime)
            ->field('order_num, order_id, order_yue_id')
            ->select();
        if($order){
            Db::startTrans();
            try{
                foreach($order as $k => $v){
                    // 订单状态
                    Db::table('up_goods_order')
                        ->where('order_id', $v['order_id'])
                        ->update([
                            'order_canecl_time' => date('Y-m-d H:i:s'),
                            'order_status' => 8
                        ]);
                    // 修改约稿状态
                    Db::table('up_yue')->where('yue_id', $v['order_yue_id'])->setField('yue_status', 4);
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    
    /**
     * 拍卖商品，24小时未付款，取消订单，押金不退
     * 每分钟--已跑
     */
    public function paimaiOrderStatus(){
        $datetime = date('Y-m-d H:i:s', strtotime('-24 hours'));
        $order = Db::table('up_goods_order')
            ->where('order_type', 2)
            ->where('order_status', 1)
            ->where('order_create_time', '<=', $datetime)
            ->field('order_num, order_goods_id, order_spec_id, order_id')
            ->select();
        if($order){
            Db::startTrans();
            try{
                foreach($order as $k => $v){
                    // 订单状态
                    Db::table('up_goods_order')
                        ->where('order_id', $v['order_id'])
                        ->update([
                            'order_canecl_time' => date('Y-m-d H:i:s'),
                            'order_status' => 8
                        ]);
                    // 释放库存
                    Db::table('up_goods_spec')->where('spec_id', $v['order_spec_id'])->setInc('spec_stock');
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    
    /**
     * 在拍卖活动时间内，超过半个小时没人竞价，以最高竞价生成订单
     * 每分钟执行一次--已跑
     */
    public function createPaimaiOrder(){
        // 拍卖中的商品
        $goods = Db::table('up_goods')
            ->where('goods_status', 1)
            ->where('goods_type', 2)
            ->where('goods_sta', 2)
            ->field('goods_id')
            ->select();
        // 如果有符合的商品，查找竞价记录
        if($goods){
            // 半个小时内有没有竞价记录，如果有，就不做处理，如果没有，就生成订单，结束拍卖
            foreach($goods as $k => $v){
                $datetime = date('Y-m-d H:i:s', strtotime('-30 minute'));
                $exist = Db::table('up_goods_jing')
                    ->where('gj_goods_id', $v['goods_id'])
                    ->where('gj_datetime', '>=', $datetime)
                    ->find();
                if(!$exist){
                    // 竞价记录
                    $jing = Db::table('up_goods_jing')
                        ->where('gj_goods_id', $v['goods_id'])
                        ->where('gj_status', 1)
                        ->field('gj_user_id, gj_goods_id, gj_new_price')
                        ->find();
                    if($jing){
                        $this->createOrder($jing);
                    }
                }
            }
        }
    }
    
    /**
     * 拍卖正常结束，如果没有该拍卖的订单并且有拍卖纪录，则以最后一个买卖的记录生成订单，
     * 如果没有拍卖纪录，只改变商品场次状态
     * 每分钟执行一次--已跑
     */
    public function overPaimaiOrder(){
        $date = date('Y-m-d');
        $time = date('H:i');
        $datetime = $date . ' ' . $time;
        // 拍卖已结束,未生成订单的商品
        $goods = Db::table('up_goods')
            ->where('goods_status', 1)
            ->where('goods_type', 2)
            ->where('goods_sta', 3)
            ->where('goods_activity_end_datetime', '<=', $datetime)
            ->where('goods_is_order', 1)
            ->field('goods_id')
            ->select();
        if($goods){
            // 有没有生成过订单
            foreach($goods as $k => $v){
                // 竞价记录
                $jing = Db::table('up_goods_jing')
                    ->where('gj_goods_id', $v['goods_id'])
                    ->where('gj_status', 1)
                    ->field('gj_user_id, gj_goods_id, gj_new_price')
                    ->find();
                if($jing){
                    $this->createOrder($jing);
                }else{
                    // 修改参加场次状态->已结束,是否生成订单->不需要生成订单
                    Db::table('up_goods')
                        ->where('goods_id', $v['goods_id'])
                        ->update(['goods_sta' => 3, 'goods_is_order' => 3]);
                }
            }
        }
    }
    
    /**
     * 拍卖落选用户退押金
     * 每分钟
     */
    public function paimaiReturn(){
        // 已结束的、没有退款的、落选的竞拍记录
        $jing = Db::table('up_goods_jing')
            ->where('gj_status', 2)
            ->where('gj_over', 2)
            ->where('gj_is_return', 1)
            ->field('gj_goods_id, gj_user_id')
            ->find();
        if($jing){
            // 押金订单
            $order = Db::table('up_goods_order')
                ->where('order_type', 5)
                ->where('order_status', 2)
                ->where('order_goods_id', $jing['gj_goods_id'])
                ->where('order_buy_user_id', $jing['gj_user_id'])
                ->field('order_id, order_number, order_paimai_ya_price, order_pay_type, order_USD_price, order_return_number')
                ->find();
            if($order){
                // TODO:其他类型退款
                $return_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT); // 退款订单号
                if($order['order_pay_type'] == 1){ // 微信
                    import('returnprice.Wx', EXTEND_PATH);
                    $wx = new Wx(config('weixin'));
                    $return = $wx->weixiReturn($order['order_paimai_ya_price'], $order['order_paimai_ya_price'], $order['order_number'], $return_number);
                }elseif($order['order_pay_type'] == 2){ // 支付宝
                    import('returnprice.Ali', EXTEND_PATH);
                    $ali = new Ali(config('ali'));
                    $return = $ali->aliReturn($order['order_paimai_ya_price'], $order['order_number']);
                }elseif($order['order_pay_type'] == 3){ // 银联
                    import('returnprice.Upacp', EXTEND_PATH);
                    $upacp = new Upacp();
                    $return = $upacp->yinLianRefund($return_number, $order['order_return_number'], $order['order_pay_price']);
                }elseif($order['order_pay_type'] == 4){ // visa
                    
                }else{ // PayPal
                    import('returnprice.Paypal', EXTEND_PATH);
                    $payPal = new Paypal();
                    $return = $payPal->returnPrice($order['order_USD_price'], $order['order_return_number']);
                }
                if($return['status'] == 200){
                    Db::startTrans();
                    try{
                        // 修改订单状态
                        $update = [
                            'order_status' => 6
                        ];
                        if($order['order_pay_type'] == 1){
                            $update['order_return_number'] = $return_number;
                        }
                        if($order['order_pay_type'] == 3){
                            $update['order_upacp_return_number'] = $return_number;
                        }
                        Db::table('up_goods_order')
                            ->where('order_id', $order['order_id'])
                            ->update($update);
                        // 修改竞价记录状态
                        Db::table('up_goods_jing')
                            ->where('gj_goods_id', $jing['gj_goods_id'])
                            ->where('gj_user_id', $jing['gj_user_id'])
                            ->setField('gj_is_return', 2);
                        Db::commit();
                    }catch(\Exception $e){
                        Db::rollback();
                    }
                }
            }
        }
    }
    
    /**
     * 更新拍卖商品、秒杀商品参加的场次状态
     * 每分钟---已跑
     */
    public function updateGoodsStatus(){
        $date = date('Y-m-d');
        $time = date('H:i');
        $datetime = $date . ' ' . $time;
        // 拍卖、秒杀 未开始->进行中
        Db::table('up_goods')
//            ->where('goods_status', 1)
            ->where('goods_type', 'IN', '2,3')
            ->where('goods_sta', 1)
            ->where('goods_activity_start_datetime', '<=', $datetime)
//            ->where('goods_activity_end_datetime', '>', $datetime)
//            ->select();
            ->setField('goods_sta', 2);
        // 拍卖、秒杀   进行中->已结束
        Db::table('up_goods')
//            ->where('goods_status', 1)
            ->where('goods_type', 'IN', '2,3')
            ->where('goods_sta', 2)
            ->where('goods_activity_end_datetime', '<=', $datetime)
            ->setField('goods_sta', 3);
    }
    
    /**
     * 将确认收货后24小时的订单，更新成已完成状态（order_aftersale_status = 2），此状态下，不可以申请售后
     * 同时，将订单金额转到画师余额,入余额明细表
     * 每分钟---已跑
     */
    public function changeOrderToOver(){
        $datetime = date('Y-m-d H:i:s', strtotime('-1 day'));
        $list = Db::table('up_goods_order')
            ->where('order_status', 'IN', '4,9')
            ->where('order_aftersale_status', 1)
            ->where('order_type', 'IN', '1,2,3,4')
            ->where('order_over_time', '<=', $datetime)
            ->field('order_id, order_pay_price, order_sail_user_id')
            ->select();
        if($list){
            Db::startTrans();
            try{
                foreach($list as $k => $v){
                    // 修改订单状态
                    Db::table('up_goods_order')
                        ->where('order_id', $v['order_id'])
                        ->update([
//                            'order_status' => 10,
                            'order_aftersale_status' => 2
                        ]);
        
                    // 余额明细表
                    $detail = [
                        'bd_user_id' => $v['order_sail_user_id'],
                        'bd_price' => $v['order_pay_price'],
                        'bd_order_id' => $v['order_id'],
                        'bd_type' => 1,
                        'bd_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_balance_detail')->insert($detail);
                    
                    // 画师余额
                    Db::table('up_u_user')->where('user_id', $v['order_sail_user_id'])->setInc('user_balance', $v['order_pay_price']);
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    
    /**
     * 将拒绝售后24小时后的订单，更新成已完成状态（order_aftersale_status = 2），此状态下，不可以申请售后
     * 同时，将订单金额转到画师余额,入余额明细表
     * 每分钟---已跑
     */
    public function changeRefuseToOver(){
        $datetime = date('Y-m-d H:i:s', strtotime('-1 day'));
        $list = Db::table('up_goods_order')
            ->where('order_status', 7)
            ->where('order_aftersale_status', 1)
            ->where('order_type', 'IN', '1,2,3,4')
            ->where('order_do_aftersale_time', '<=', $datetime)
            ->field('order_id, order_pay_price, order_sail_user_id')
            ->select();
        if($list){
            Db::startTrans();
            try{
                foreach($list as $k => $v){
                    // 修改订单状态
                    Db::table('up_goods_order')
                        ->where('order_id', $v['order_id'])
                        ->update([
//                            'order_status' => 10,
                            'order_aftersale_status' => 2
                        ]);
                    
                    // 余额明细表
                    $detail = [
                        'bd_user_id' => $v['order_sail_user_id'],
                        'bd_price' => $v['order_pay_price'],
                        'bd_order_id' => $v['order_id'],
                        'bd_type' => 1,
                        'bd_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_balance_detail')->insert($detail);
                    
                    // 画师余额
                    Db::table('up_u_user')->where('user_id', $v['order_sail_user_id'])->setInc('user_balance', $v['order_pay_price']);
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    
    /**
     * 生成拍卖订单以及其他相关操作
     * @param $jing    押金记录数组
     */
    public function createOrder($jing){
        // 押金订单
        $ya_order = Db::table('up_goods_order')
            ->where('order_type', 5)
            ->where('order_goods_id', $jing['gj_goods_id'])
            ->where('order_buy_user_id', $jing['gj_user_id'])
            ->where('order_status', 2)
            ->field('order_sail_user_id, order_spec_id, order_addr_id')
            ->find();
    
        $order_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT); // 订单号
        $order = [
            'order_number' => $order_number,
            'order_goods_price' => $jing['gj_new_price'],
            'order_pay_price' => $jing['gj_new_price'],
            'order_num' => 1,
            'order_goods_id' => $jing['gj_goods_id'],
            'order_buy_user_id' => $jing['gj_user_id'],
            'order_sail_user_id' => $ya_order['order_sail_user_id'],
            'order_type' => 2,
            'order_spec_id' => $ya_order['order_spec_id'],
            'order_is_coupon' => 2,
            'order_my_coupon_id' => 0,
            'order_coupon_price' => 0,
            'order_addr_id' => $ya_order['order_addr_id'],
            'order_create_time' => date('Y-m-d H:i:s')
        ];
        Db::startTrans();
        try{
            // 生成订单
            Db::table('up_goods_order')->insert($order);
            // 减库存
            Db::table('up_goods_spec')->where('spec_id', $ya_order['order_spec_id'])->setDec('spec_stock');
            // 修改竞价状态
            Db::table('up_goods_jing')->where('gj_goods_id', $jing['gj_goods_id'])->setField('gj_over', 2);
            // 商品拍得者修改状态->暂时不需退款，订单支付完成后，再退款
            Db::table('up_goods_jing')
                ->where('gj_goods_id', $jing['gj_goods_id'])
                ->where('gj_user_id', $jing['gj_user_id'])
                ->setField('gj_is_return', 3);
            // 修改参加场次状态->已结束,未生成订单->已生成订单
            Db::table('up_goods')
                ->where('goods_id', $jing['gj_goods_id'])
                ->update(['goods_sta' => 3, 'goods_is_order' => 2]);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
        }
    }
}